const app = getApp();
var time = 0;
var count = 0;
var count1 = 0;
var startPoint = 0;
var startEle = 0;
let timeevent = ''
Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    view: {
      height: null
    },
    currentTab: 0, //预设当前项的值
    currentTab1: 0, //预设当前项的值
    showModalType: false,
    Temp: true,
    showInitialPage: true,
    showInitialTime: 5,
    collectData: false,
    filterStyleStatus: false,
    filterTypeStatus: false,
    showDialog: false,
    controllsPlay: false,
    videoSrc: '',
    showDialog1: false,
    choiceFilterList: ["时间", "风格", "类型", "收藏"],
    choiceFilterStyleList: [],
    choiceFilterTypeList: [],
    opendid: '',
    choiceFilterDataShow: [],
    transition: '',
    sortData: 0,
    scrollPageNum: 1,
    dateParams: {
      orderFlag: 0,
      styleCode: '',
      typeCode: ''
    },
    swiperIndex: 0,
    copySwiperIndex: 0,
    outUrl: false,
    commonUrl: app.globalData.commonUrl,
    showVrData: [],
    showVRInitDataStatus: -1,
    showVRInitDataCont: '收藏项目',
    collectVrProjectDataStatus: false,
    collectVrProjectDataStatusData: [],
    collectDataMy: [],
    isHaveCollectData: false,
    showStatusSubs: false,
    orderTotalPage: '',
    onLoading: false,
    noMoreData: false,
    bindDownLoad: false,
    interval: 2000,
    duration: 2000,
    autoplay: false,
    showUpJStatus: false,
    styleCodeValue: '',
    typeCodeValue: '',
    scrollTop: {
      scroll_top: 0
    },
    winHeight: "", //窗口高度
    initCount: 1,
    istoleft: false,
    isleft: false,
    isright: false
  },
  //保存图片到本地
  saveImgToLocal: function (e) {
    let procode = e.currentTarget.dataset.procode;
    let saveImgToLocalParams = {
      userToken: wx.getStorageSync('sessionid'),
      openId: wx.getStorageSync('sessionid'),
      proCode: procode
    };
    app.handlerPost('/api/account/doShareMiniImg.do', saveImgToLocalParams, "GET").then((res) => {
      if (res.data.code == "SUCCESS") {
        let imgurl = res.data.data;
        wx.downloadFile({
          url: imgurl,
          success: function (res) {
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: function (res) {
                wx.showToast({
                  title: '保存到相册成功',
                  icon: 'success',
                  duration: 2000
                });
              },
              fail: function (err) {
                console.log(err);
                if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                  console.log("当初用户拒绝，再次发起授权");
                  wx.openSetting({
                    success(settingdata) {
                      console.log(settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                      } else {
                        console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                      }
                    }
                  })
                }
              },
            })
          },
          fail: function () {
            console.log('fail')
          }
        })
      }
    }).catch((errMsg) => {
      console.log(errMsg);
    });
  },

  subsUpdata: function (e) {
    this.setData({
      showStatusSubs: !this.data.showStatusSubs
    });
  },

  gosharingPage(e) {
    // let itemCode = e.currentTarget.dataset.number;
    // if ( == 1) {
    //     itemCode = '00' + itemCode
    // } else if (itemCode.toString().length == 2) {
    //     itemCode = '0' + itemCode
    // }
    wx.navigateTo({
      url: "../sharingPage/sharingPage?type=1&itemId=" + e.currentTarget.dataset.itemid
    })
  },

  //收藏相关
  collectVrProjectData: function (e) {
    let item = e.currentTarget.dataset.currentitem;
    let index = e.currentTarget.dataset.index;
    if (this.data.collectVrProjectDataStatusData[index]) {
      this.data.collectVrProjectDataStatusData[index] = false;
      this.cancelCollectVrPocject(item);
    } else {
      this.data.collectVrProjectDataStatusData[index] = true;
      this.collectVrPocject(item);
    }
    this.setData({
      collectVrProjectDataStatusData: this.data.collectVrProjectDataStatusData
    });
  },
  //收藏相关
  collectVrPocject: function (item) {
    let collectParams = {
      userToken: wx.getStorageSync('sessionid'),
      proId: item.id,
      proType: 0,
      remark: item.userName,
      title: item.proName
    };
    app.handlerPost('/api/account/doJoinMyFavorite.do', collectParams, "GET").then((res) => {
      if (res.data.code == "SUCCESS") {
        wx.showToast({
          title: '收藏成功',
          icon: 'success',
          duration: 2000
        })
      }
    }).catch((errMsg) => {
      console.log(errMsg);
    });
  },
  //收藏相关
  cancelCollectVrPocject: function (item) {
    let collectParams = {
      userToken: wx.getStorageSync('sessionid'),
      proId: item.id,
      proType: 0,
      title: item.proAddress + ' · ' + item.userName + ' · ' + item.userName,
    };
    app.handlerPost('/api/account/doRemoveMyFavorite.do', collectParams, "GET").then((res) => {
      if (res.data.code == "SUCCESS") {
        wx.showToast({
          title: '取消成功',
          icon: 'success',
          duration: 2000
        })
      }
    }).catch((errMsg) => {
      console.log(errMsg);
    });
  },
  //跳vr页面
  goOutUrl: function (e) {
    this.setData({
      filterStyleStatus: false,
      filterTypeStatus: false
    });
    let outUrl = e.currentTarget.dataset.outurl;
    let type = e.target.dataset.type;
    if (type == 'collect' || type == 'transmit' || type == 'turnLocalImg' || type == 'dingyue') {
      return;
    }
    wx.navigateTo({
      url: '../vrPageExhibt/vrPageExhibt?outUrl=' + outUrl
    })
  },
  //去搜索页
  toSearchPage: function () {
    this.setData({
      filterStyleStatus: false,
      filterTypeStatus: false
    });
    wx.navigateTo({
      url: '../projectSearchPage/projectSearchPage'
    })
  },

  swiperChange(e) {
    this.setData({
      showVRInitDataStatus: -1,
      swiperIndex: e.detail.current
    });
  },
  //触摸开始事件
  getVideoModal: function (e) {
    this.setData({
      filterStyleStatus: false,
      filterTypeStatus: false
    });
    if (e.currentTarget.dataset.src) {
      this.setData({
        videoSrc: e.currentTarget.dataset.src
      });
    }
    this.setData({
      showDialog: !this.data.showDialog
    });
    if (!this.data.showDialog) {
      this.setData({
        controllsPlay: false
      });
    } else {
      this.setData({
        controllsPlay: true
      });
    }
  },

  //切换模式，幻灯片和列表模式
  changeModalType: function () {
    this.setData({
      showModalType: !this.data.showModalType,
      swiperIndex: 0,
      filterStyleStatus: false,
      filterTypeStatus: false
    });
  },

  bindDownLoad: function (e) {
    let that = this;
    that.setData({
      bindDownLoad: true
    });
    if (that.data.orderTotalPage == this.data.scrollPageNum) {
      that.setData({
        noMoreData: true,
        onLoading: false,
        filterStyleStatus: false,
        filterTypeStatus: false
      });
      return;
    } else {
      this.data.scrollPageNum++;
      that.setData({
        // onLoading:true,
        scrollPageNum: this.data.scrollPageNum,
        filterStyleStatus: false,
        filterTypeStatus: false
      });
    }
    // console.log(this.data.currentTab1);
    that.getFilterDataP(this.data.currentTab1);

  },

  refresh: function (e) {

    let that = this;
    if (this.data.scrollPageNum == 1) {
      return
    } else {
      this.data.scrollPageNum--;
      that.setData({
        scrollPageNum: this.data.scrollPageNum,
      });
    }
    setTimeout(() => {
      that.getFilterDataP(this.data.currentTab1);
    }, 100);

  },

  getFilterDataP: function (data) {
    let that = this;
    if (data == 0) {
      wx.showLoading({
        title: '加载中',
      });
      if (this.data.dateParams.orderFlag == 0) {
        this.data.dateParams.orderFlag = 0;
      } else {
        this.data.dateParams.orderFlag = 1;
      }
      this.data.dateParams['page.page'] = this.data.scrollPageNum;
      that.fetchAddressList(that.choiceFilterData('/api/plateForm/plateFormPage.do', this.data.dateParams, 'GET'));
    } else if (data == 1) {
      wx.showLoading({
        title: '加载中',
      });
      that.fetchAddressList(that.choiceFilterData('/api/plateForm/plateFormPage.do', {
        'page.page': this.data.scrollPageNum
      }, 'GET'));
    } else if (data == 2) {
      wx.showLoading({
        title: '加载中',
      });
      that.fetchAddressList(that.choiceFilterData('/api/plateForm/plateFormPage.do', {
        'page.page': this.data.scrollPageNum
      }, 'GET'));
    }
  },
  //分类筛选
  choiceFilterType: function (e) {
    var that = this;
    this.setData({
      scrollPageNum: 0,
      "scrollTop.scroll_top": 0
    })

    if (this.data.currentTab1 == e.target.dataset.index && e.target.dataset.index != 0) {
      if (this.data.currentTab1 == 1) {
        this.setData({
          currentTab1: 1,
          scrollPageNum: 1,
          filterStyleStatus: !this.data.filterStyleStatus,
          filterTypeStatus: false,
        });
      } else if (this.data.currentTab1 == 2) {
        this.setData({
          currentTab1: 2,
          scrollPageNum: 1,
          filterStyleStatus: false,
          filterTypeStatus: !this.data.filterTypeStatus,
        });
      }
      return;
    } else {
      if (e.target.dataset.index == 0) {
        wx.showLoading({
          title: '加载中',
        });
        this.setData({
          filterStyleStatus: false,
          filterTypeStatus: false,
        });
        if (this.data.dateParams.orderFlag == 0) {
          this.setData({
            showUpJStatus: true
          });
          this.data.dateParams.orderFlag = 1;

        } else {
          this.setData({
            showUpJStatus: false
          });
          this.data.dateParams.orderFlag = 0;
        }
        this.data.dateParams['page.page'] = this.data.scrollPageNum;
        that.fetchAddressList(that.choiceFilterData('/api/plateForm/plateFormPage.do', this.data.dateParams, 'GET'));
      } else if (e.target.dataset.index == 1) {
        count++;
        if (count <= 1) {
          this.setData({
            filterStyleStatus: !this.data.filterStyleStatus,
            filterTypeStatus: false,
          });
        } else {
          this.setData({
            filterStyleStatus: !this.data.filterStyleStatus,
            filterTypeStatus: false,
          });
          if (this.data.filterStyleStatus) {
            this.setData({
              currentTab1: 1,
              scrollPageNum: 1,
            });
            return;
          } else {
            wx.showLoading({
              title: '加载中',
            });
            that.fetchAddressList(that.choiceFilterData('/api/plateForm/plateFormPage.do', {
              'page.page': this.data.scrollPageNum
            }, 'GET'));
          }
        }
      } else if (e.target.dataset.index == 2) {
        count1++;
        if (count1 <= 1) {
          this.setData({
            filterTypeStatus: !this.data.filterTypeStatus,
            filterStyleStatus: false,
          });
        } else {
          this.setData({
            filterTypeStatus: !this.data.filterTypeStatus,
            filterStyleStatus: false,
          });
          if (this.data.filterTypeStatus) {
            this.setData({
              currentTab1: 2,
              scrollPageNum: 1,
            });
            return;
          } else {
            wx.showLoading({
              title: '加载中',
            });
            that.fetchAddressList(that.choiceFilterData('/api/plateForm/plateFormPage.do', {
              'page.page': this.data.scrollPageNum
            }, 'GET'));
          }
        }
      } else {
        this.setData({
          filterStyleStatus: false,
          filterTypeStatus: false
        });
      }
      if (e.target.dataset.index == 3) {
        wx.showLoading({
          title: '加载中',
        });
        this.setData({
          collectData: true,
          filterStyleStatus: false,
          filterTypeStatus: false,
          choiceFilterDataShow: [],
        });
        that.getMyCollectData();
      } else {
        this.setData({
          collectData: false
        });
      }
    }
    this.setData({
      currentTab1: e.target.dataset.index,
      scrollPageNum: 1,
    });

  },
  getMyCollectData: function () {
    wx.showLoading({
      title: '加载中',
    });
    app.handlerPost('/api/account/doMyFavoritePage.do', {
      userToken: wx.getStorageSync('sessionid'),
      type: 0
    }, "GET").then((res) => {
      if (res.data.code == "SUCCESS") {
        let data = res.data.data;
        this.setData({
          collectDataMy: data,
          isHaveCollectData: true
        });

      }
      app.fetchAddressList();
    }).catch((errMsg) => {
      console.log(errMsg);
    });
  },
  fetchAddressList(callback) {
    setTimeout(res => {
      wx.hideLoading();
    }, 500);
    if (callback) {
      callback();
    }

  },
  choiceFilterData: function (url, params, type) {
    app.handlerPost(url, params, type).then((res) => {
      let that = this;
      if (res.data.mes = 'SUCCESS') {
        let choiceFilterDataShow = res.data.data.items;
        if (that.data.choiceFilterDataShow == '') {
          that.setData({
            orderTotalPage: res.data.data.totalPage,
            noData: true
          })
        }
        if (this.data.scrollPageNum == 1) {
          this.setData({
            choiceFilterDataShow: choiceFilterDataShow,
          });
        } else {
          this.setData({
            choiceFilterDataShow: this.data.choiceFilterDataShow.concat(choiceFilterDataShow),
          });
        }
      }
    }).catch((errMsg) => {
      console.log(errMsg);
    });
  },
  getVrData: function () {
    this.data.collectVrProjectDataStatusData = [];
    app.handlerPost('/api/plateForm/plateFormPage.do', {
      userToken: wx.getStorageSync('sessionid')
    }, 'GET').then((res) => {
      if (res.data.code = 'SUCCESS') {
        let data = res.data.data.items;
        this.setData({
          showVrData: data
        });
        for (var i = 0; i < data.length; i++) {
          if (data[i].isMyFavorite == 'F') {
            this.data.collectVrProjectDataStatusData.push(false);
          } else {
            this.data.collectVrProjectDataStatusData.push(true);
          }
        }
        this.setData({
          collectVrProjectDataStatusData: this.data.collectVrProjectDataStatusData
        });
      }

    }).catch((errMsg) => {
      console.log(errMsg);
    });
  },
  //风格筛选
  choiceStyle: function (e) {
    wx.showLoading({
      title: '加载中',
    });
    let that = this;
    let styleValue = this.data.choiceFilterStyleList[e.target.dataset.index];
    this.data.choiceFilterList[1] = styleValue.dictName;
    this.data.styleCodeValue = styleValue.dictCode;
    this.setData({
      choiceFilterDataShow: [],
      collectData: false,
    });
    // 模仿网络请求
    // ,typeCode:this.data.typeCodeValue
    that.fetchAddressList(that.choiceFilterData('/api/plateForm/plateFormPage.do', {
      styleCode: styleValue.dictCode
    }, 'GET'));
    this.setData({
      filterStyleStatus: !this.data.filterStyleStatus,
      choiceFilterList: this.data.choiceFilterList
    });
  },
  choiceType: function (e) {
    wx.showLoading({
      title: '加载中',
    });
    let typeValue = this.data.choiceFilterTypeList[e.target.dataset.index];
    this.data.choiceFilterList[2] = typeValue.dictName;
    this.data.typeCodeValue = typeValue.dictCode;
    let that = this;
    // 模仿网络请求
    this.setData({
      choiceFilterDataShow: [],
      collectData: false,
    });
    // styleCode:this.data.styleCodeValue,
    that.fetchAddressList(that.fetchAddressList(that.choiceFilterData('/api/plateForm/plateFormPage.do', {
      typeCode: typeValue.dictCode
    }, 'GET')));
    this.setData({
      filterTypeStatus: !this.data.filterTypeStatus,
      choiceFilterList: this.data.choiceFilterList
    });
  },
  switchTab: function (e) {
    // this.setData({
    //     currentTab: e.detail.current
    // });
  },
  getDictPageData: function () {
    app.handlerPost('/api/plateForm/dictPage.do').then((res) => {
      if (res.data.msg == "SUCCESS") {
        let choiceFilterStyleList = res.data.data.aList;
        let choiceFilterTypeList = res.data.data.bList;
        choiceFilterStyleList.unshift({
          "dictName": "风格",
          "dictCode": ""
        });
        choiceFilterTypeList.unshift({
          "dictName": "类型",
          "dictCode": ""
        });
        this.setData({
          choiceFilterStyleList: choiceFilterStyleList,
          choiceFilterTypeList: choiceFilterTypeList
        });
      }
    }).catch((errMsg) => {
      // console.log(errMsg);
    })
  },
  onReady: function (res) {
    this.videoContext = wx.createVideoContext('myVideo')
  },
  onShow: function () {
    if (app.globalData.setValue) {
      this.setData({
        showModalType: true,
        collectData: true,
        currentTab1: 3,
        filterStyleStatus: false,
        filterTypeStatus: false
      });
      this.getMyCollectData();
      app.globalData.setValue = false;
    }

    var that = this;
    //  高度自适应
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR;
        that.setData({
          winHeight: calc
        });
      }
    });
  },

  showVRInitData(e) {
    this.setData({
      showVRInitDataStatus: this.data.showVRInitDataStatus ? this.data.showVRInitDataStatus == e.currentTarget.dataset.index ? -1 : e.currentTarget.dataset.index : -1,
      autoplayleft: !this.data.autoplayleft,
      autoplay: this.data.isright && !this.data.isleft ? !this.data.autoplay : this.data.autoplay
    });

    setTimeout(() => {
      !this.data.isright && this.data.isleft && this.data.autoplayleft ? this.jishi(): ''
    }, 100);
  },

  jishi() {
    timeevent = setInterval(() => {
      let index = this.data.swiperIndex;
      if (index == 0) {
        index = this.data.showVrData.length - 1
      } else {
        index--
      }
      this.setData({
        swiperIndex: index
      })
    }, 2500) 
  },
  
  stopmove() {
    if (timeevent) clearInterval(timeevent);
  },

  toleft() {
    this.setData({
      autoplay: false,
      autoplayleft: true,
      isleft: !this.data.isleft,
      isright: false
    })
    this.stopmove();
    this.data.isleft ? this.jishi() : ''
  },

  touchmove() {
    this.data.autoplayleft ? this.toleft() : '';
  },

  toright() {
    this.stopmove();
    this.setData({
      autoplay: !this.data.autoplay,
      autoplayleft: false,
      isleft: false,
      isright: !this.data.isright
    })
  },

  onLoad: function (options) {
    if (options.projectnum) {
      this.setData({
        swiperIndex: parseInt(options.projectnum)
      })
    }
    wx.login({
      success: function (r) {
        if (options.type == 'share') {
          wx.setStorageSync('parentOpenId', options.parentOpenId);
          app.login({
            code: r.code,
            parentOpenId: options.parentOpenId
          });
        } else {
          app.login({
            code: r.code
          });
        }
      }
    });
    var that = this;
    this.setData({
      showModalType: false,
      currentTab1: 0,
      filterStyleStatus: false,
      filterTypeStatus: false
    });
    this.getVrData();
    that.fetchAddressList(that.choiceFilterData('/api/plateForm/plateFormPage.do', this.data.dateParams, 'GET'));
    this.getDictPageData();
  },

  onPageScroll: function (e) {
    console.log(1);
  },

  onShareAppMessage: function (res) {
    let parentOpenId = wx.getStorageSync('sessionid'),
      path;
    if (res.from === 'button') {
      let projectnum = this.data.swiperIndex;
      path = '/pages/index/index?parentOpenId=' + parentOpenId + '&type=share&projectnum=' + projectnum;
    } else {
      path = '/pages/index/index?parentOpenId=' + parentOpenId + '&type=share'
    }
    return {
      title: 'VR+视频+清单丨大手笔制作丨所见即所得',
      path: path,
      imageUrl: "https://vr2018.oss-cn-beijing.aliyuncs.com/vr/shareimg/meijingshare-2.jpg",
      success: function (res) {
        console.log(res);
      },
      fail: function (res) {
        console.log(res);
      }
    }
  },
  footerTap: app.footerTap
});